package com.xxx.car.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理json字符串与对象之间关系的工具类
 */
public class GsonUtils {
	private static final Logger logger = LoggerFactory.getLogger(GsonUtils.class);

	private GsonUtils(){}
	private static volatile ObjectMapper mapper = new ObjectMapper();

	public static String toJson(Object obj) {
		return toJson(obj, null, false);
	}
	
	public static String toJson(Object obj, Boolean isExportNull) {
		return toJson(obj, null, false, isExportNull);
	}
	
	public static String toJson(Object obj, String datePattern) {
		return toJson(obj, datePattern, false);
	}
	
	public static String toJson(Object obj, String datePattern, Boolean isPrettyPrinting) {
		return toJson(obj, datePattern, isPrettyPrinting, null);
	}

	/**
	 * 对象转成json字符串
	 * @param obj  要转的对象
	 * @param datePattern   日期格式
	 * @param isPrettyPrinting  是否格式化json字符串
	 * @param isExportNull   是否输出null值
	 * @return
	 */
	public static String toJson(Object obj, String datePattern, Boolean isPrettyPrinting, Boolean isExportNull) {
		GsonBuilder builder = new GsonBuilder();
		
		if (isPrettyPrinting != null && isPrettyPrinting) {
			builder.setPrettyPrinting();
		}
		if (StringUtils.isEmpty(datePattern)) {
			datePattern = "yyyy-MM-dd HH:mm:ss";
		}
		if (isExportNull != null && isExportNull) {
			builder.serializeNulls();
		}
		builder.disableHtmlEscaping();
		builder.setDateFormat(datePattern);
		Gson gson = builder.create();
		return gson.toJson(obj);
	}

	/**
	 * json字符串转化为对象
	 * @param jsonStr
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> T jsonStrToEntity(String jsonStr, Class<T> clazz) {
		Gson gson = new GsonBuilder().create();
		return gson.fromJson(jsonStr, clazz);
	}


	/***
	 * json数组 转 list 对象
	 * @param jsonStr
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> List<T> jsonToList(String jsonStr,Class<T> clazz){
		try {
			CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, clazz);
			List<T> lst = mapper.readValue(jsonStr, listType);
			return lst;
		} catch (IOException e) {
			logger.error("{}",e);
			return new ArrayList<>();
		}
	}

	/**
	 * 把JavaBean转换为json字符串
	 *
	 * @param object
	 * @return
	 */
	public static String toJSonStr(Object object) {
		try {
			return mapper.writeValueAsString(object);
		} catch (Exception e) {
			logger.error("{}", e);
			return null;
		}
	}


	
}
